let myaudio = document.querySelector('#myaudio')
let musicR = document.querySelector('.ply')
let wrapperBox = document.querySelector('.lyric')
let lyric = []
let alreadyBox = document.querySelector('.already')
let durationBox = document.querySelector('.duration')
let rateBox = document.querySelector('.rate')

//这呢
let allSpeed = document.querySelector('.s_mind')
let redKnew = document.querySelector('.red_knew')
let redRate = document.querySelector('.red')


// 处理播放时间和进度
const format = function format(num) {
  let minutes = Math.floor(num / 60)
  let seconds = Math.ceil(num - minutes * 60)
  if (minutes < 10) minutes = '0' + minutes
  if (seconds < 10) seconds = '0' + seconds
  return `${minutes}:${seconds}`
}

const handleTimeAndRate = function handleTimeAndRate() {
  let { currentTime, duration } = myaudio
  if (isNaN(currentTime) || isNaN(duration)) return
  if (currentTime >= duration) {
    currentTime = 0
  }
  alreadyBox.innerHTML = format(currentTime)
  durationBox.innerHTML = format(duration)
  rateBox.style.width = `${currentTime / duration * 100}%`
}

// 等待audio加载完基础信息,绑定总时间等
myaudio.onloadedmetadata = handleTimeAndRate
$sub.on('music', handleTimeAndRate)

// 获取歌词绑定数据
const render = function render(lyric) {
  //此歌曲不需要解析出标题和作者
  // 解析出标题和作者
  //    let title = lyric.match(/\[ti&#58;([^\]]+)\]/),
  //    author = lyric.match(/\[ar&#58;([^\]]+)\]/)
  //  if (title) h2Box.innerHTML = title[1]
  //  if (author) h3Box.innerHTML = author[1]
  // 解析歌词
  let arr = []

  lyric.replace(/\[(\d+):(\d+).(?:\d+)\]([^/\n]+)/g, (_, minutes, seconds, text) => {
    // console.log(minutes ,seconds ,text);
    arr.push({
      minutes,
      seconds,
      text
    })
  });

  // 歌词绑定
  let str = ``
  arr.forEach(item => {
    let { minutes, seconds, text } = item
    str += `<p minutes = "${minutes}" seconds = "${seconds}">${text}</P>`
  })
  wrapperBox.innerHTML = str

  // 其他操作
  lyricList = Array.from(wrapperBox.querySelectorAll('p'))
}

const queryData = function queryData() {
  return new Promise(resolve => {
    let xhr = new XMLHttpRequest;
    xhr.open('GET', './Alljson/music/精卫.json');
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let data = JSON.parse(xhr.responseText);
        resolve(data);
      }
    };
    xhr.send();
  });
};

queryData().then(value => {
  return value.lyric
}).then(lyric => {
  render(lyric)
})



// 音乐的播放和暂停
// 控制歌词对应
let n = 0
$sub.on('music', function () {
  // 获取当前已经播放时间的分钟和秒
  let { currentTime, duration } = myaudio
  let [minutes, seconds] = format(currentTime).split(':')
  let H = lyricList[0].offsetHeight
  // 从所有歌词中筛选出和 播放时间匹配的 & 不匹配的集合
  let matchArr = []
  let unmatchArr = []
  lyricList.forEach(item => {
    let a = item.getAttribute('minutes')
    let b = item.getAttribute('seconds')
    if (a === minutes && b === seconds) {
      matchArr.push(item)
      return
    }
    unmatchArr.push(item)
  })

  // 一经发现再做处理
  if (matchArr.length > 0) {
    matchArr.forEach(item => item.classList.add('active1'))
    unmatchArr.forEach(item => item.classList.remove('active1'))
    // 匹配的同时 wrapper的挪动
    n += matchArr.length
    if (n > 4) {
      wrapperBox.style.transform = `translateY(${-(n - 4) * H}px)`
    }
  }


  // 播放完毕的处理
  if (currentTime >= duration) {
    myaudio.pause()
    musicR.className = 'ply'
    
    wrapperBox.style.transform = `translateY(0)`
    lyricList.forEach(item => item.classList.remove('active'))
    n = 0
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }


})
let timer = null

//歌曲进度条拖动
allSpeed.addEventListener("click", function (event) {
  let x = event.offsetX;//获取鼠标所在位置
  let bfb = x / 466 * 100;
  redRate.style.width = bfb + "%";
  myaudio.currentTime = myaudio.duration * +bfb / 100;
  wrapperBox.style.transform = `translateY(${-(8.68 * myaudio.currentTime)}px)`
});

redRate.addEventListener("click", function (event) {
  let x = event.offsetX;//获取鼠标所在位置
  let bfb = x / 466 * 100;
  redRate.style.width = bfb + "%";
  myaudio.currentTime = myaudio.duration * +bfb / 100;
  wrapperBox.style.transform = `translateY(${(8.68 * myaudio.currentTime)}px)`
});


// redKnew.addEventListener("mousedown", function (event) {
//   let disX = event.clientX - redKnew.offsetLeft;
//   document.onmousemove = function (event) {
//     let l = event.clientX - disX;
//     if (l < 0) {
//       l = -12
//     } else if (l > allSpeed.offsetWidth - redKnew.offsetWidth) {
//       l = allSpeed.offsetWidth - redKnew.offsetWidth + 12
//     }
//     redKnew.style.left = l + "px"
//     // let scale = 1/(allSpeed.offsetWidth - redKnew.offsetWidth)
//     let x = event.offsetX;//获取鼠标所在位置
//     let bfb = l/ 466 * 100;
//     redRate.style.width = bfb + "%";
//     myaudio.currentTime = myaudio.duration * +bfb / 100;

//     event.onmouseup = function (e) {
//      e.onmousemove = function(){
//         let bfb = l/ 466 * 100;
//         redRate.style.width = bfb + "%";
//         myaudio.currentTime = myaudio.duration * +bfb / 100;
//         e.onmouseup = "null"
//       };
//   };
//   }
// });

musicR.addEventListener('click', function () {
  if (myaudio.paused) {
    // 当前暂停 让其播放
    myaudio.play()
    musicR.className = 'ply1'
    if (!timer) {
      $sub.emit('music')
      timer = setInterval(() => {
        $sub.emit('music')
      }, 1000)
    }
    return
  }
  // 当前播放 让其暂停
  myaudio.pause()
  musicR.className = 'ply'
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})